//////////////////////////////////////////////////////////////////////
/**
* 处理流媒体的检测
*/


//////////////////////////////////////////////////////////////////////
/**
* 流媒体主类	CTP_Embed
*/

var CTP_Embed = function(doc){

	var that = this;
	
	// 格式化URL
    function Normalize(url) {
        var inURL = url;
        var outURL = "";
        while (inURL.length > 0) {
            if (inURL.indexOf("../") === 0) {
                inURL = inURL.substring(3);
            } else if (inURL.indexOf("./") === 0) {
                inURL = inURL.substring(2);
            } else if (inURL.indexOf("/./") === 0) {
                inURL = inURL.substring(2);
            } else if (inURL.indexOf("/../") === 0) {
                inURL = inURL.substring(3);
                outURL = outURL.substring(0, outURL.lastIndexOf("/"));
            } else if (inURL.indexOf("/..") === 0) {
                inURL = "/" + inURL.substring(3);
                outURL = outURL.substring(0, outURL.lastIndexOf("/"));
            } else if (inURL.indexOf("/.") === 0) {
                inURL = "/" + inURL.substring(2);
            } else if (inURL === "." || inURL === "..") {
                inURL = "";
            } else {
                var end = inURL.indexOf("/");
                if (end > 0) {
                    outURL = outURL + inURL.substring(0, end);
                    inURL = inURL.substring(end);
                } else if (end === 0) {
                    end = inURL.substring(1).indexOf("/") + 1;
                    if (end > 0) {
                        outURL = outURL + inURL.substring(0, end);
                        inURL = inURL.substring(end);
                    } else {
                        outURL = outURL + inURL;
                        inURL = "";
                    }
                } else {
                    outURL = outURL + inURL;
                    inURL = "";
                }
            }
        }
        return outURL;
    }

	// 返回完整URL
    function fixUrl(url) {
        //check whether the URL is correct.
        if (url.indexOf(doc.location.protocol) == 0) {
            return Normalize(url);
        } else {
            if (url.charAt(0) == "/") {
                return Normalize(doc.location.protocol + "//" + doc.location.host + url);
            } else {
                return Normalize(doc.location.protocol + "//" + doc.location.host + doc.location.pathname.substring(0, doc.location.pathname.lastIndexOf("/")) + "/" + url);
            }
        }
    }

	// 由链接地址得到文件名
    function getFilename(url) {
        var filename = url;
        var index = filename.indexOf("?");
        if (index > -1) {
            filename = filename.substring(0, index); //remove the query.
        }
        index = filename.indexOf("#");
        if (index > -1) {
            filename = filename.substring(0, index); //remove the fragment.
        }
        return filename.substring(filename.lastIndexOf("/") + 1);
    }
	
	
	// 得到RealTime真实地址
    function getRealQTLink(url) {
        var ioserv = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
        var channel = ioserv.newChannel(url, null, null);
        var stream = channel.open();
        if (channel instanceof Components.interfaces.nsIHttpChannel && channel.responseStatus != 200) {
            return url;
        }
        var bstream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
        bstream.setInputStream(stream);
        if (bstream) {
            var nextAtom = getAtom("moov", bstream);
            if ((nextAtom) && (nextAtom = getAtom("rmra", nextAtom))) {
                if (nextAtom = getAtom("rmda", nextAtom)) {
                    if (nextAtom = getAtom("rdrf", nextAtom)) {
                        if (nextAtom = getAtom("url ", nextAtom, true)) {
                            var dataRefSize = 0;
                            for (var i = 3; i > -1; i--) {
                                if (nextAtom.available()) {
                                    dataRefSize += (nextAtom.read8() << i);
                                } else {
                                    bstream.close();
                                    stream.close();
                                    return url;
                                }
                            }
                            var realURL = "";
                            for (i = 4; i < dataRefSize + 4; i++) {
                                if (nextAtom.available()) {
                                    realURL += String.fromCharCode(nextAtom.read8());
                                } else {
                                    bstream.close();
                                    stream.close();
                                    return url;
                                }
                            }
                            var eol = realURL.indexOf('\u0000'); //remove extra information            
                            if (eol > -1) {
                                realURL = realURL.substring(0, eol);
                            }
                            bstream.close();
                            stream.close();
                            return url.substring(0, url.lastIndexOf("/") + 1) + realURL;
                        }
                    }
                }
            }
            bstream.close();
            stream.close();
        }
        return url;
    }

    function getAtom(name, stream, ignoreSize) {
        var size = 0;
        for (var i = 3; i > -1; i--) {
            if (stream.available()) {
                size += (stream.read8() << i);
            } else {
                return false;
            }
        }
        if (ignoreSize || size > 1) {
            var typeName = "";
            for (i = 0; i < 4; i++) {
                if (stream.available()) {
                    typeName += String.fromCharCode(stream.read8());
                } else {
                    return false;
                }
            }
            if (typeName == name) {
                return stream;
            }
        }
        return false;
    }

	//返回节点的媒体类型
    function getMimetype(node) {
        var mimetype = node.getAttribute("type");
        if (mimetype == null) {
            var params = node.getElementsByTagName("param");
			var mimes = Array.prototype.filter.call(params,
            function(element, index, array) {
                return element.getAttribute("name") === "type" && element.getAttribute("value") != null;
            });
            if (mimes.length > 0) {
                mimetype = mimes[0];
            } else {
                mimetype = "";
            }
        }
        return mimetype;
    }

	// 返回节点URL
    function getUrls(node, attributes, spliter) {
        var urls = new Array();
        Array.prototype.forEach.call(attributes,
        function(element, index, array) {
            var url = node.getAttribute(element);
            if (url == null) {
                var params = node.getElementsByTagName("param");
                var subUrls = Array.prototype.filter.call(params,
                function(subElement, subIndex, subArray) {
                    return subElement.getAttribute("name") === element && subElement.getAttribute("value") != null;
                });
                if (subUrls.length > 0) {
                    urls = urls.concat(subUrls[0].getAttribute("value").split(spliter));
                }
            } else {
                urls = urls.concat(url.split(spliter));
            }
        });
        return urls;
    }

	// 添加到Embed列表中
    this.Add = function(doc) {

        function getContent(tagname, attributes, spliter) {
            var nodes = doc.getElementsByTagName(tagname);
            Array.prototype.forEach.call(nodes,
            function(element, index, array) {
                var mimetype = getMimetype(element);
                var urls = getUrls(element, attributes, spliter);
                urls = urls.map(function(single) {
                    return fixUrl(single);
                });
                if (mimetype == "video/quicktime") {
					// QuickTime媒体
                    urls = urls.concat(urls.map(function(single) {
                        return getRealQTLink(single);
                    }));
                }
                urls.forEach(function(element, index, array) {
                    var filename = getFilename(element);
					//添加到Embed列表中
					myDump("embedAdded: " + filename);
                    that.Objects.push({
                        url: element,
                        filename: filename,
                        mime: mimetype
                    });
                });
            });
        }

        var tags = [{
            tagName: "embed",
            attributes: ["src"]
        },
        {
            tagName: "applet",
            attributes: ["archive"],
            spliter: ","
        },
        {
            tagName: "object",
            attributes: ["href", "src", "source", "data", "movie"]
        },
        {
            tagName: "bgsound",
            attributes: ["src"]
        }];
		
		//对每一种节点类型获取相应的Embed
        tags.forEach(function(element, index, array) {
            getContent(element.tagName, element.attributes, element.spliter);
        });
		
		//remove duplicated entries
	    that.Objects = that.Objects.filter(function(element, index, array) { 
            var next = index + 1;
            if (next < array.length) {
                if (element.filename.toLowerCase() === array[next].filename.toLowerCase()) {
                    return false;
                }
            }
            return true;
        });
    };

    this.Objects = [];
    this.Add(doc);	
};

//////////////////////////////////////////////////////////////////////
/**
* 流媒体检测主类 CTP_EmbedListener
*/
var CTP_EmbedListener = {
	pageLoadListener:function(event){
		if (event.originalTarget instanceof HTMLDocument) {
			var doc = event.originalTarget;
			var embed = new CTP_Embed(doc);
			doc.addEventListener("DOMNodeInserted", function(event) {
			  if(gBrowser.selectedBrowser == gBrowser.getBrowserForDocument(doc)) {
				CTP_Embed.Add(event.target.parentNode);
				CTP_EmbedListener.addToEmbed(embed, true);
			  }      
			}, false);
			CTP_EmbedListener.addToEmbed(embed);
		}
	},
	addToEmbed:function(embed){
		myDump("A Embed Object Detected.");
		
		embed.Objects.forEach(function(element, index, array) {
			//if(CTP_CheckURL(element.url) == 0){
				myDump("A Embed URL Added To List: " + element.url);
				CTP_addToURLList(element.url);				
				CTP_setListHeight();
								
				//显示提示
				CTP_EmbedListener.showWin();
			//}	
		});
		
	},
	
	showWin:function(){
		//提示检测到流媒体	
		var tooltipH = document.getElementById("cplayer_tooltip");
		tooltipH.showPopup(document.getElementById("cplayer_text_bar"),-1,-1,"tooltip","topright","bottomright");
		setTimeout("CTP_EmbedListener.hideWin()", 10000);
	},
	
	hideWin:function(){
		var tooltipH = document.getElementById("cplayer_tooltip");
		tooltipH.hidePopup();
	}
	
};


//////////////////////////////////////////////////////////////////////
/**
* 添加监听
*/

function AddEmbedListener() {
	myDump("Embed Listener Added.");
	//make sure we're running inside the browser window.
	if(typeof(gBrowser) != "undefined") {
	  //don't know why, but useCapture must be true or else it won't work.
	  gBrowser.addEventListener("load", CTP_EmbedListener.pageLoadListener, true);
	}
}
